package org.example.task.validation;

import cn.hutool.core.bean.BeanUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.example.task.annotation.DueDateAfterStart;

import java.time.LocalDateTime;

public class DueDateAfterStartValidator implements ConstraintValidator<DueDateAfterStart, Object> {
    private String startField;
    private String dueField;

    @Override
    public void initialize(DueDateAfterStart constraintAnnotation) {
        this.startField = constraintAnnotation.startField();
        this.dueField = constraintAnnotation.dueField();
    }

    @Override
    public boolean isValid(Object bean, ConstraintValidatorContext constraintValidatorContext) {
        try {
            LocalDateTime start = (LocalDateTime) BeanUtil.getProperty(bean, startField);
            LocalDateTime due = (LocalDateTime) BeanUtil.getProperty(bean, dueField);
            if (start == null || due == null) {
                return true;
            }
            if (!due.isAfter(start)&&!due.isEqual(start)) {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext
                        .buildConstraintViolationWithTemplate(constraintValidatorContext
                                .getDefaultConstraintMessageTemplate()).addPropertyNode(dueField)
                        .addConstraintViolation();
                return false;
            }
            return true;
        }catch (Exception e){
            return false;
        }

    }

}
